﻿using Common;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IntelligentFiles.HcCommon
{
    class BarCode
    {
        static SerialPort code = new SerialPort();
        /// <summary>
        /// 读取的条码值
        /// </summary>
        static string strCode = "";
        public static void getCode()
        {
            try
            {
                OpenCom();

            }
            catch (Exception ex)
            {
                CommonApi.writeLog("开锁异常," + ex.ToString());
            }
        }
        /// <summary>
        /// 端口打开
        /// </summary>
        public static bool OpenCom()
        {
            if (!code.IsOpen)
            {
                code.PortName = ComParam.lockCom;
                code.BaudRate = 9600;//串口波特率，固定值
                code.Parity = System.IO.Ports.Parity.None;
                code.StopBits = System.IO.Ports.StopBits.One;
                code.DataBits = 8;//数据位
                code.Handshake = System.IO.Ports.Handshake.None;
                code.Encoding = Encoding.ASCII;//编码方式
                code.DataReceived += new SerialDataReceivedEventHandler(code_DataReceived);
                code.Open();
            }
            return code.IsOpen;
        }
        /// <summary>
        /// 接收扫码器信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void code_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                int iByteLen = code.BytesToRead;
                byte[] iBytes;
                iBytes = new byte[iByteLen];
                code.Read(iBytes, 0, iByteLen);
                strCode = System.Text.Encoding.Default.GetString(iBytes);
                if (strCode != "")
                { 
                    //接收值后 调用接口


                }
            }
            catch(Exception ex)
            {
                CommonApi.writeLog("扫码器信息回调异常," + ex.ToString());
            }
        }
    }
}
